<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene"></Category>
    <!--展示某一个三级分类下的平台属性与属性值-->
    <el-card shadow="always" style="margin-top: 10px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          size="default"
          :icon="Plus"
          style="margin-bottom: 10px"
          @click="addAttr"
          :disabled="!categoryStore.c3Id"
          >添加属性</el-button
        >
        <!--属性控件--->
        <el-tree :data="treeData"></el-tree>

        <el-table border stripe :data="attrList">
          <el-table-column label="序号" width="80" type="index" align="center">
          </el-table-column>
          <el-table-column
            label="属性名称"
            width="120"
            prop="attrName"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag
                style="margin: 0px 3px"
                class="ml-2"
                :type="attrVal.id % 2 == '0' ? 'success' : 'warning'"
                v-for="(attrVal, index) in row.attrValueList"
                :key="attrVal.id"
                >{{ attrVal.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="removeAttr(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <!-- 添加属性|修改属性的结构 -->
        <el-form ref="form" :inline="true">
          <el-form-item label="属性名">
            <!-- 收集属性名字 -->
            <el-input
              placeholder="请你输入属性的名字"
              size="normal"
              clearable
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!attrParams.attrName"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button @click="cancel">取消</el-button>
        <!-- 将来表格展示属性值的地方 -->
        <el-table
          border
          stripe
          style="margin: 10px 0px"
          :data="attrParams.attrValueList"
        >
          <el-table-column type="index" align="center" width="80" label="序号">
          </el-table-column>
          <el-table-column label="属性值">
            <!-- row到底是谁?who are you? -->
            <template #="{ row, $index }">
              <el-input
                :ref="(vc) => (inputArr[$index] = vc)"
                v-if="row.flag"
                placeholder="请你输入属性值"
                size="small"
                v-model="row.valueName"
                @blur="toLook(row, $index)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
          >保存</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
  UploadFilled,
} from "@element-plus/icons-vue";
import useCategoryStore from "../../../stores/category";
//
//引入分类的仓库
import useCategryStore from "../../../stores/category";
let categoryStore = useCategoryStore();
//引入组合式APIwatch
import { watch, ref, reactive, nextTick, onUnmounted } from "vue";
//引入请求函数
import {
  reqAttrList,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from "../../../api/product/attr/attr";
import { ElMessage } from "element-plus";
//引入lodash里面cloneDepp---深拷贝
import _ from "lodash";



//引入数据类型
import type {attrResponseData,attrModel,attrValueModel} from '../../../api/product/attr/model/attr'

//存储平台属性的数据
let attrList = ref<attrResponseData>([]);
//定义数组ref类型数据，将来存储el-input组件的实例
let inputArr = ref<any>([]);
//将来添加或者修改属性需要参数
let attrParams = reactive<attrModel>({
  attrName: "", //新增|修改以后属性名字
  categoryId: "", //代表平台属性归属于手机这个三级分类下的
  categoryLevel: 3, //代表几级分类
  attrValueList: [
    //存储新增|修改属性值的数据
    // {
    //   valueName: "string", //属性值名字
    // },
  ],
});

//定义响应式变量控制场景切换---[2个]
let scene = ref<number>(0);

let treeData = ref([]);
//监听三级分类的ID变化，如果发生变化需要发请求
watch(
  () => categoryStore.c3Id,
  () => {
    //判断:三级分类ID保证有数据
    if (categoryStore.c3Id == "") return;
    //获取平台属性方法
    getAttrList();
  }
);
//获取商品属性的方法
const getAttrList = async () => {
  let result:attrResponseData = await reqAttrList(
    categoryStore.c1Id,
    categoryStore.c2Id,
    categoryStore.c3Id
  );

  //存储数据---平台属性
  attrList.value = result;
  //测试属性控件
  //  treeData.value = result.map(item=>{
  //      return {
  //          label:item.attrName,
  //          children:item.attrValueList.map(item=>{
  //               return {
  //                   label:item.valueName,

  //               }
  //          })
  //      }
  //  });
  //  console.log(treeData.value);
};
//添加属性按钮的回调
const addAttr = () => {
  //切换场景
  scene.value = 1;
  //点击添加属性按钮每一次都要情况带给服务器参数
  //情况数据:浅拷贝
  Object.assign(attrParams, {
    attrName: "",
    categoryId: categoryStore.c3Id, //每一次进入到添加|修改属性的时候，清空数据|同时把三级分类ID收集到
    categoryLevel: 3,
    attrValueList: [],
  });
};
//取消按钮的点击事件[两个]
const cancel = () => {
  //切换场景为0
  scene.value = 0;
};

//添加属性值按钮的回调
const addAttrValue = () => {
  //向属性值数组添加元素
  attrParams.attrValueList.push({
    valueName: "",
    //给每一个属性值添加标记:用来切换编辑模式与查看模式
    flag: true,
  });
  //获取el-input组件实例,数组最后这个元素
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

//input失却焦点变为查看模式
//row:即为添加属性值对象
const toLook = (row:attrValueModel, $index:number) => {
  //属性值一些非法情况需要判断---属性值为空
  if (row.valueName.trim() == "") {
    ElMessage({
      type: "warning",
      message: "亲爱的属性值不能为空",
    });
    //属性值数组把当前非法属性值对象干掉
    attrParams.attrValueList.splice($index, 1);
    //代表后面代码不能执行
    return;
  }
  //属性值重名
  let repeat = attrParams.attrValueList.find((item) => {
    //先把数组当中自身扣除去
    if (row != item) {
      return row.valueName === item.valueName;
    }
  });

  //如果出现重复
  if (repeat) {
    ElMessage({
      type: "warning",
      message: `${repeat.valueName}重复?`,
    });
    //属性值数组把当前非法属性值对象干掉
    attrParams.attrValueList.splice($index, 1);
    return;
  }

  row.flag = false;
  console.log(inputArr.value);
};
//div点击切换为编辑模式
const toEdit = (row:attrValueModel, $index:number) => {
  row.flag = true;

  //点击div切换显示el-input，需要聚焦
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
//保存按钮
const save = async () => {
  //参数整理一下:属性值的数组flag属性不需要--->干掉
  attrParams.attrValueList.forEach((item) => {
    if (item.hasOwnProperty("flag")) {
      //删除某一个属性
      delete item.flag;
    }
  });
  //  attrParams.attrValueList =  attrParams.attrValueList.map((item)=>{
  //      return {
  //        valueName:item.valueName
  //      }
  //  })
  try {
    //添加属性成功
    await reqAddOrUpdateAttr(attrParams);
    //切换场景
    scene.value = 0;
    //提示
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
    });
    //获取全部最新的属性的数据
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};

//修改按钮
const updateAttr = (row:attrModel) => {
  //点击修改属性按钮切换场景为1
  scene.value = 1;
  //row:即为用户想要修改的已有的属性与属性值
  //目前底下的写法：是将row，基本类型数值深拷贝[属性名]，引用类型数值浅拷贝[属性值]
  //深拷贝:JSON.parse + JSON.stringify
  Object.assign(attrParams, _.cloneDeep(row));
};

//删除已有属性
const removeAttr = async (row:attrModel) => {
  try {
    //删除已有属性成功
    await reqDeleteAttr(row.id);
    //提示信息
    ElMessage({
      type: "success",
      message: `删除${row.attrName}成功`,
      duration: 500, //约束提示信息的事件
    });
    //再次获取最新的属性的数据
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "error",
      message: `删除${row.attrName}失败`,
      duration: 500,
    });
  }
};

//组件销毁钩子
onUnmounted(() => {
  //组件销毁的时候。情况仓库里面的数据
  categoryStore.c1Id = "";
  categoryStore.c2Id = "";
  categoryStore.c3Id = "";
  categoryStore.c1List = [];
  categoryStore.c2List = [];
  categoryStore.c3List = [];
});
</script>

<style scoped>
</style>